#!/usr/bin/env python
# -- coding utf-8 --

from os.path import join

import random

from kapybara.language import *
from kapybara.database import FileDatabase

def pick_language(options, prompt):
    for i, o in sorted(options.iteritems())[1:]:
        print(u'{0}: {1}'.format(i, o.name(i)))
    while True:
        choice = input(prompt)
        if choice in sorted(options.keys())[1:]:
            return options[choice]
        print('Invalid choice, try again.')

def pick_option(options, e_class, src_language, dst_language):
    answer = options[0]
    random.shuffle(options)
    print(
        u'What expression is equivalent to "{0}" (theme: {1}) in {2}'.format(
            answer.name(src_language),
            e_class.name(src_language),
            dst_language.name(src_language)
        )
    )
    for i, o in enumerate(options):
        print(u'{0}: {1}'.format(i+1, o.name(dst_language)))
    while True:
        choice = raw_input(u'Pick option 1-5 (or q to quit): ')
        if choice == 'q':
            return False
        if choice.isdigit():
            choice = int(choice)
            if 1 <= choice <= 5:
                if options[choice-1] == answer:
                    print(u'Correct answer!')
                    return True
                else:
                    print(
                        u'Wrong answer. {0} means {1} in {2}. Try again.'.format(
                            options[choice-1].name(dst_language).capitalize(),
                            options[choice-1].name(src_language),
                            dst_language.name(src_language)
                        )
                    )
            else:
                print('Invalid option!')
        else:
            print('Invalid option!')

def test():
    # Connect to database
    db = FileDatabase(join('db', 'vocabulary.kap'))

    # Pick a language
    src_language = pick_language(db.languages(),
        'Choose your native language: ')
    print(u'Native Language: {0}'.format(src_language.name(src_language)))

    dst_language = pick_language(db.languages(),
        'Choose your target language: ')
    print(u'Target Language: {0}'.format(dst_language.name(dst_language)))

    while True:
        e_classes = src_language.expression_classes().values()
        e_class = random.choice(e_classes)
        expressions = src_language.expressions(e_class).values()
        options = random.sample(expressions, 5)
        if not pick_option(options, e_class, src_language, dst_language):
            break

if __name__=='__main__':
    test()
